package cn.loveq.android.widget;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.loveq.android.Constant;
import cn.loveq.android.R;
import cn.loveq.android.util.TimeUtils;

import com.spoledge.aacplayer.AACFileChunkPlayer;
import com.spoledge.aacplayer.AACPlayer;
import com.spoledge.aacplayer.ArrayAACPlayer;
import com.spoledge.aacplayer.ArrayDecoder;
import com.spoledge.aacplayer.Decoder;
import com.spoledge.aacplayer.PlayerCallback;

/**
 * 
 * 
 * 项目名称：loveq4Weibo 
 * 类名称：RadioGalleryViewItem 
 * 类描述：收音机Gallery的模块 
 * 创建人：李伟豪
 * 创建时间：2011-12-5 下午04:35:28 
 * 
 * @version
 * 
 */
public class RadioGalleryViewItem extends RelativeLayout implements View.OnClickListener, PlayerCallback, VerticalSeekBar.OnSeekBarChangeListener {
	private static final String TAG = "RadioGalleryViewItem";
	private static final String MMSADDRESS = "mms://live.fm993.com.cn/musicfm";
	private static final int PROGRESS_CHANGED = 0x001;
	private static final int CURRENT_TIME = 0x002;
	private static final int STARTPROGRAM_TIME = 0x003;
	private static final int PER_SECOND = 1000;
	private int playeredTime = 0;// 已经播放的时间
	private Context mContext;
	private LayoutInflater mInflater;
	private LinearLayout radioMainView;
	private RelativeLayout soundControlBar;// 声音控制面板
	private Handler uiHandler;
	
	private Button btnMMSWMA;// 开始按钮
	private Button btnStop;// 停止按钮
	private Button btnSuspend;// 暂停按钮
	private Button btnSound;// 声音按钮
	private TextView currentTime;// 当前时间
	private TextView playedTimer;// 已经播放的时间
	private ImageView radioLogo;// logo
	private VerticalSeekBar bar;
	private ProgressBar progress;
	private TextView txtPlayStatus;// 当前状态：
	private EditText txtBufAudio;// AUDIO_BUFFER_CAPACITY
	private EditText txtBufDecode;// DECODE_BUFFER_CAPACITY
	// private TextView txtStatus;
	private AudioManager mAudioManager;
	private boolean playerStarted;// 播放标识
	private boolean isPause = false;
	public static boolean timerFlag;// 系统时间标识
	private boolean isFirstPlay;//是第一次播放

	private MyTimerTask myTimerTask;
	private StartPlayedTimerTask startPlayedTimerTask;
	private AACPlayer aacPlayer;
	private AACFileChunkPlayer aacFileChunkPlayer;
	private Thread thread;
	private Thread playedThread;
	/**
	 * Decoder features: FAAD | FFmpeg | OpenCORE
	 */
	private int dfeatures;

	public RadioGalleryViewItem(Context context, int position) {
		super(context);
		this.mContext = context;
		// main
		initLayout();
		mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
		initUI();
		enableButtons();
		
		playeredTime = 0;
		isFirstPlay = false;
		uiHandler = new Handler();
	}

	private void initLayout(){
		this.mInflater = LayoutInflater.from(mContext);
		radioMainView = (LinearLayout) this.mInflater.inflate(R.layout.radio_main_layout, null);
		this.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
		this.addView(radioMainView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
	}
	
	/**
	 * 初始化UI
	 */
	private void initUI() {
		btnMMSWMA = (Button) radioMainView.findViewById(R.id.radio_btn_start);
		txtPlayStatus = (TextView) radioMainView.findViewById(R.id.current_status);
		btnSound = (Button) radioMainView.findViewById(R.id.btn_sound);
		btnStop = (Button) radioMainView.findViewById(R.id.radio_btn_stop);
		btnSuspend = (Button) radioMainView.findViewById(R.id.radio_btn_suspend);
		currentTime = (TextView) radioMainView.findViewById(R.id.current_time);
		playedTimer = (TextView) radioMainView.findViewById(R.id.played_timer);
		radioLogo = (ImageView) radioMainView.findViewById(R.id.radio_logo);
		// txtStatus = (TextView)
		// radioMainView.findViewById(R.id.view_main_text_what);
		// txtBufAudio = (EditText)
		// radioMainView.findViewById(R.id.radio_main_text_bufaudio);
		// txtBufDecode = (EditText)
		// radioMainView.findViewById(R.id.radio_main_text_bufdecode);
		// progress = (ProgressBar)
		// radioMainView.findViewById(R.id.radio_main_progress);
		bar = (VerticalSeekBar) radioMainView.findViewById(R.id.voice_control);

		soundControlBar = (RelativeLayout) radioMainView.findViewById(R.id.sound_control_bar);

		txtBufAudio = new EditText(mContext);
		txtBufDecode = new EditText(mContext);

		txtBufAudio.setText(String.valueOf(AACPlayer.DEFAULT_AUDIO_BUFFER_CAPACITY_MS));
		txtBufDecode.setText(String.valueOf(AACPlayer.DEFAULT_DECODE_BUFFER_CAPACITY_MS));

		dfeatures = ArrayDecoder.getFeatures();

		bar.setProgress(getCurrentVolume());
		btnMMSWMA.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnSuspend.setOnClickListener(this);
		btnSound.setOnClickListener(soundLintener);
		bar.setOnSeekBarChangeListener(this);// 添加事件监听
		initTimer();
	}

	private void initTimer() {
		myTimerTask = new MyTimerTask();
		timerFlag = true;
		thread = new Thread(myTimerTask);
		thread.start();
		// timer.schedule(myTimerTask, 2000);
	}

	@Override
	public void playerStarted() {
		uiHandler.post(new Runnable() {
			public void run() {
				btnMMSWMA.setEnabled(false);
				btnStop.setEnabled(true);

				txtPlayStatus.setText(mContext.getString(R.string.text_buffering));
				// progress.setProgress(0);
				// progress.setVisibility(View.VISIBLE);

				playerStarted = true;
			}
		});
	}

	@Override
	public void playerStopped(final int perf) {
		uiHandler.post(new Runnable() {
			public void run() {
				enableButtons();
				btnStop.setEnabled(false);
				txtBufAudio.setEnabled(true);
				txtBufDecode.setEnabled(true);
				// txtStatus.setText(R.string.text_stopped);
				if (isPause) {
					txtPlayStatus.setText("暂停,缓存：" + perf + "%");
				} else {
					txtPlayStatus.setText("停止");
				}
				Log.i(TAG, "-----加载缓存 " + perf + " %");
				// progress.setVisibility(View.INVISIBLE);
				if (radioLogo != null) {
					radioLogo.clearAnimation();

				}
				playedThread = null;
				startPlayedTimerTask = null;
				playerStarted = false;
			}
		});

	}

	/**
	 * 将开始按钮设为可用
	 */
	private void enableButtons() {
		if ((dfeatures & Decoder.DECODER_FFMPEG_WMA) != 0)
			btnMMSWMA.setEnabled(true);
	}

	@Override
	public void playerPCMFeedBuffer(final boolean isPlaying, final int audioBufferSizeMs, final int audioBufferCapacityMs) {
		uiHandler.post(new Runnable() {
			public void run() {
				// progress.setProgress(audioBufferSizeMs * progress.getMax() /
				// audioBufferCapacityMs);
				// TODO
				if (isPlaying) {
					txtPlayStatus.setText(R.string.text_playing);
					if (playedThread == null) {
						startPlayedTimerTask = new StartPlayedTimerTask();

						playedThread = new Thread(startPlayedTimerTask);
						playedThread.start();
						
						//final Animation animationIn = AnimationUtils.loadAnimation(mContext, R.anim.logo_fade_in);
						final Animation animationOut = AnimationUtils.loadAnimation(mContext, R.anim.logo_fade_out);
						
						radioLogo.startAnimation(animationOut);
						//radioLogo.setAnimation(animationOut);
						
						
					}
					Log.i(TAG, "播放动画");
				}
			}
		});
	}

	@Override
	public void playerException(final Throwable t) {
		uiHandler.post(new Runnable() {
			public void run() {
				new AlertDialog.Builder(mContext).setTitle(R.string.text_exception).setMessage(t.toString()).setNeutralButton(R.string.button_close, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				}).show();

				// txtStatus.setText(R.string.text_stopped);

				if (playerStarted)
					playerStopped(0);
			}
		});

	}

	@Override
	public void onClick(View v) {
		try {
			switch (v.getId()) {
			case R.id.radio_btn_start:
				int state = checkNetworkInfo();
				if(state == Constant.ConnectType.CONNECT_TYPE_WIFI){
					isPause = false;
					start(Decoder.DECODER_FFMPEG_WMA);
					btnMMSWMA.setEnabled(false);
					// txtStatus.setText(R.string.text_using_MMSWMA);
					
				}else if(state == Constant.ConnectType.CONNECT_TYPE_VPN){
					if(!isFirstPlay){
						showNetworkDialog();
					}else{
						isPause = false;
						start(Decoder.DECODER_FFMPEG_WMA);
						btnMMSWMA.setEnabled(false);
					}
				}else if(state == Constant.ConnectType.CONNECT_TYPE_UNKNOW){
					showErrorNetworkDialog();
				}

				break;
			case R.id.radio_btn_suspend:
				isPause = true;
				pause();
				break;
			case R.id.radio_btn_stop:
				isPause = false;
				stop();
				break;
			}
		} catch (Exception e) {
			Log.e("AACPlayerActivity", "exc", e);
		}
	}

	/**
	 * 开始
	 */
	private void start(int decoder) {
		stop();
		aacPlayer = new ArrayAACPlayer(ArrayDecoder.create(decoder), this, getInt(txtBufAudio), getInt(txtBufDecode));
		// aacPlayer.playAsync("mms://218.30.114.31/guangdong_zhujiang_fm974");
		aacPlayer.playAsync(MMSADDRESS);
	}

	/**
	 * 暂停
	 */
	private void pause() {
		if (aacFileChunkPlayer != null) {
			aacFileChunkPlayer.stop();
		}
		if (aacPlayer != null) {
			aacPlayer.stop();
		}
	}

	/**
	 * 停止
	 */
	private void stop() {
		if (aacFileChunkPlayer != null) {
			aacFileChunkPlayer.stop();
			aacFileChunkPlayer = null;
		}
		if (aacPlayer != null) {
			aacPlayer.stop();
			aacPlayer = null;
		}
	}

	private int getInt(EditText et) {
		return Integer.parseInt(et.getText().toString());
	}

	/**
	 * 声音监听器
	 */
	Button.OnClickListener soundLintener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (soundControlBar.getVisibility() == View.INVISIBLE) {
				soundControlBar.setVisibility(View.VISIBLE);
			} else {
				soundControlBar.setVisibility(View.INVISIBLE);
			}
		}

	};

	/**
	 * 音乐控制,seekbar 进程改变
	 */
	@Override
	public void onProgressChanged(VerticalSeekBar VerticalSeekBar, int progress, boolean fromUser) {
		// Toast.makeText(mContext, "当前值：" + progress,
		// Toast.LENGTH_SHORT).show();
		Message msg = new Message();
		msg.arg1 = progress;
		msg.what = PROGRESS_CHANGED;
		mHandler.sendMessageDelayed(msg, 100);
	}

	/**
	 * 音乐控制,seekbar 拖动中
	 */
	@Override
	public void onStartTrackingTouch(VerticalSeekBar verticalSeekBar) {
		Toast.makeText(mContext, "拖动中", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStopTrackingTouch(VerticalSeekBar VerticalSeekBar) {
	}

	/**
	 * 设置音量
	 */
	private void setVolume(int currentProgress) {
		int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		bar.setMax(maxVolume);
		// int currentVolume =
		// mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		// bar.setProgress(currentVolume);
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentProgress * 100 / maxVolume, 0);
		Log.i(TAG, "currentVolume" + currentProgress * 100 / maxVolume);
	}

	/**
	 * 获取当初音量
	 */
	private int getCurrentVolume() {
		return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100 / 100;
	}

	/**
	 * 检查网络状态
	 */
	private int checkNetworkInfo() {
		ConnectivityManager conMan = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return Constant.ConnectType.CONNECT_TYPE_VPN;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return Constant.ConnectType.CONNECT_TYPE_WIFI;
		return Constant.ConnectType.CONNECT_TYPE_UNKNOW;

	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PROGRESS_CHANGED:
				try {
					// if (playerStarted) {
					setVolume(msg.arg1);
					// }
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case CURRENT_TIME:
				// currentTime.setText(TimeUtils.getFormateCreatedDate());
				currentTime.setText(TimeUtils.getNowTime());
				break;
			case STARTPROGRAM_TIME:
				// TODO
				playeredTime++;
				playedTimer.setText(TimeUtils.cal(playeredTime));
				break;
			default:
				break;
			}

			super.handleMessage(msg);

		}

	};

	/**
	 * 显示网络对话框
	 */
	private void showNetworkDialog() {
		Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(mContext.getText(R.string.network_info_title));
		builder.setMessage(mContext.getText(R.string.network_info_message));
		builder.setIcon(R.drawable.warn);
		builder.setPositiveButton(R.string.go_on, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				isFirstPlay = true;
				dialog.dismiss();
			}
		});
		builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialoginterface, int i) {
				System.exit(0);
			}
		});

		builder.show();
	}

	/**
	 * 显示错误网络对话框
	 */
	private void showErrorNetworkDialog(){
		Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(mContext.getText(R.string.set_network));
		builder.setMessage(mContext.getText(R.string.network_info_error));
		builder.setIcon(R.drawable.warn);
		builder.setPositiveButton(R.string.set_network, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				 mContext.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));//进入无线网络配置界面
			}
		});
		builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialoginterface, int i) {
				System.exit(0);
			}
		});

		builder.show();
	}
	
	class StartPlayedTimerTask implements Runnable {

		@Override
		public void run() {
			while (playerStarted) {

				Message msg = new Message();
				msg.what = STARTPROGRAM_TIME;
				mHandler.sendMessage(msg);
				Log.i(TAG, "StartPlayedTimerTask.....");
				try {
					Thread.sleep(PER_SECOND);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	class MyTimerTask implements Runnable {
		@Override
		public void run() {
			while (timerFlag) {
				Message msg = new Message();
				msg.what = CURRENT_TIME;
				mHandler.sendMessage(msg);
				Log.i(TAG, "timer.....");
				try {
					Thread.sleep(PER_SECOND);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
